import 'dart:convert';
import '../model/bgcContentSave.dart';
import '../model/bgcContentBo.dart';
import '../model/draftModel.dart';
import '../model/apiResponse.dart';
import '../constants/apiConstants.dart';
import '../utils/envConfig.dart';
import 'base/apiClient.dart';

class ContentService {
  final ApiClient _apiClient = ApiClient();

  // POST /pacsun/community/api/v1/bgc/content/publish
  Future<BgcContentBo> publishContent(BgcContentSave contentSave) async {
    try {
      String uri = '/api/v1/bgc/content/publish';

      // 准备请求数据
      final requestData = contentSave.toJson();

      // 输出调试信息
      print('=== ContentService 发布请求 ===');
      print('URL: ${EnvConfig.baseUrl}$uri');
      print('Headers: ${jsonEncode(ApiConstants.jsonHeaders)}');
      print('Request Data: ${jsonEncode(requestData)}');
      print('===============================');

      final response = await _apiClient.post(
        uri,
        data: requestData,
        headers: ApiConstants.jsonHeaders,
      );

      // 输出响应信息
      print('=== 发布响应 ===');
      print('Status Code: ${response.statusCode}');
      print('Response Data: ${jsonEncode(response.data)}');
      print('===============');

      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
        response.data,
        (data) => data as Map<String, dynamic>,
      );

      if (apiResponse.isSuccess && apiResponse.data != null) {
        return BgcContentBo.fromJson(apiResponse.data!);
      } else {
        throw Exception('发布内容失败: ${apiResponse.message}');
      }
    } catch (e) {
      print('=== 发布请求失败 ===');
      print('Error: $e');
      print('==================');
      throw Exception('发布内容失败: $e');
    }
  }

  // POST /pacsun/community/api/v1/bgc/content/draft
  Future<DraftModel> saveDraft(BgcContentSave contentSave) async {
    try {
      String uri = '/api/v1/bgc/content/draft';

      // 准备请求数据
      final requestData = contentSave.toJson();

      // 输出调试信息
      print('=== ContentService 保存草稿请求 ===');
      print('URL: ${EnvConfig.baseUrl}$uri');
      print('Headers: ${jsonEncode(ApiConstants.jsonHeaders)}');
      print('Request Data: ${jsonEncode(requestData)}');
      print('是否包含taskConfigId: ${contentSave.taskConfigId != null}');
      print('=================================');

      final response = await _apiClient.post(
        uri,
        data: requestData,
        headers: ApiConstants.jsonHeaders,
      );

      // 输出响应信息
      print('=== 草稿保存响应 ===');
      print('Status Code: ${response.statusCode}');
      print('Response Data: ${jsonEncode(response.data)}');
      print('==================');

      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
        response.data,
        (data) => data as Map<String, dynamic>,
      );

      if (apiResponse.isSuccess && apiResponse.data != null) {
        // 检查响应格式：有taskConfigId时返回DraftModel格式，否则返回BgcContentBo格式
        final responseData = apiResponse.data!;

        if (responseData.containsKey('taskRecordBo') &&
            responseData.containsKey('detached')) {
          // 新格式：包含完整的草稿信息（有taskConfigId时）
          print('=== 检测到新格式响应（包含taskRecordBo） ===');
          print('草稿ID: ${responseData['id']}');
          print('taskRecordId: ${responseData['taskRecordId']}');
          print('=======================================');

          return DraftModel.fromJson(responseData);
        } else {
          // 旧格式：简单的BgcContentBo格式（无taskConfigId时）
          print('=== 检测到旧格式响应（BgcContentBo格式） ===');
          final bgcContentBo = BgcContentBo.fromJson(responseData);

          // 将BgcContentBo转换为DraftModel格式
          return DraftModel(
            id: bgcContentBo.id ?? 0,
            aid: bgcContentBo.aid ?? '',
            title: bgcContentBo.title ?? '',
            content: bgcContentBo.content ?? '',
            richContent: bgcContentBo.richContent ?? '',
            images: bgcContentBo.images ?? [],
            taskRecordId: bgcContentBo.taskRecordId ?? 0,
            taskRecordBo: null,
            taskTagBoList: bgcContentBo.taskTagBoList ?? [],
            status: bgcContentBo.status ?? 'DRAFT',
            thumbnail: bgcContentBo.thumbnail,
            detached: bgcContentBo.detached ?? false,
          );
        }
      } else {
        throw Exception('保存草稿失败: ${apiResponse.message}');
      }
    } catch (e) {
      print('=== 草稿保存请求失败 ===');
      print('Error: $e');
      print('======================');
      throw Exception('保存草稿失败: $e');
    }
  }

  // PUT /pacsun/community/api/v1/bgc/content/draft - 更新草稿
  Future<bool> updateDraft(BgcContentSave contentSave) async {
    try {
      String uri = '/api/v1/bgc/content/draft';

      // 准备请求数据
      final requestData = contentSave.toJson();

      final response = await _apiClient.put(
        uri,
        data: requestData,
        headers: ApiConstants.jsonHeaders,
      );

      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
        response.data,
        (data) => data as Map<String, dynamic>,
      );

      // 只返回成功状态，不解析复杂的返回数据
      return apiResponse.isSuccess;
    } catch (e) {
      print('=== 草稿更新请求失败 ===');
      print('Error: $e');
      print('======================');
      throw Exception('更新草稿失败: $e');
    }
  }

  // POST /pacsun/community/api/v1/bgc/content/publishDraft - 发布草稿
  Future<BgcContentBo> publishDraft(BgcContentSave contentSave) async {
    try {
      String uri = '/api/v1/bgc/content/publishDraft';

      // 准备请求数据
      final requestData = contentSave.toJson();

      // 输出调试信息
      print('=== ContentService 发布草稿请求 ===');
      print('URL: ${EnvConfig.baseUrl}$uri');
      print('Headers: ${jsonEncode(ApiConstants.jsonHeaders)}');
      print('Request Data: ${jsonEncode(requestData)}');
      print('==================================');

      final response = await _apiClient.post(
        uri,
        data: requestData,
        headers: ApiConstants.jsonHeaders,
      );

      // 输出响应信息
      print('=== 发布草稿响应 ===');
      print('Status Code: ${response.statusCode}');
      print('Response Data: ${jsonEncode(response.data)}');
      print('==================');

      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
        response.data,
        (data) => data as Map<String, dynamic>,
      );

      if (apiResponse.isSuccess && apiResponse.data != null) {
        try {
          // 添加详细的调试信息来帮助定位问题
          final data = apiResponse.data!;
          print('=== 开始解析BgcContentBo ===');
          print('data keys: ${data.keys}');
          print('id: ${data['id']} (${data['id'].runtimeType})');
          print('status: ${data['status']} (${data['status'].runtimeType})');
          print(
              'taskRecordId: ${data['taskRecordId']} (${data['taskRecordId'].runtimeType})');

          return BgcContentBo.fromJson(data);
        } catch (parseError) {
          print('=== BgcContentBo解析失败 ===');
          print('Parse Error: $parseError');
          print('Error Type: ${parseError.runtimeType}');
          print('========================');
          throw Exception('解析发布响应失败: $parseError');
        }
      } else {
        throw Exception('发布草稿失败: ${apiResponse.message}');
      }
    } catch (e) {
      print('=== 发布草稿请求失败 ===');
      print('Error: $e');
      print('=====================');
      throw Exception('发布草稿失败: $e');
    }
  }

  // 根据任务记录ID获取草稿内容
  Future<DraftModel> getDraftByTaskRecordId(int taskRecordId) async {
    try {
      String uri = '/api/v1/bgc/content/draft/task/$taskRecordId';

      final response = await _apiClient.get(
        uri,
        headers: {
          'Accept': '*/*',
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      );

      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
        response.data,
        (data) => data as Map<String, dynamic>,
      );

      if (apiResponse.isSuccess && apiResponse.data != null) {
        return DraftModel.fromJson(apiResponse.data!);
      } else {
        throw Exception('获取草稿失败: ${apiResponse.message}');
      }
    } catch (e) {
      throw Exception('获取草稿失败: $e');
    }
  }
}
